#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

void SLPrint(SL** sl)
{
	assert(sl);
	SL* ptail = *sl;
	while (ptail)
	{
		printf("%d->", ptail->date);
		ptail = ptail->next;
	}
	printf("NULL\n");
}
SL* BuyNode(SLDateType index)
{
	SL* buynode = (SL*)malloc(sizeof(SL));
	if (buynode == NULL)
	{
		perror("malloc error!\n");
		exit(1);
	}
	buynode->date = index;
	buynode->next = NULL;
	return buynode;
}
void SLPushBack(SL** sl, SLDateType index)
{
	assert(sl);
	SL* newnode = BuyNode(index);
	if (*sl == NULL)
	{
		*sl = newnode;
	}
	else
	{
		SL* ptail = *sl;
		while (ptail->next)
		{
			ptail = ptail->next;
		}
		ptail->next = newnode;
	}
}
void SLPushFront(SL** sl, SLDateType index)
{
	assert(sl);
	SL* newnode = BuyNode(index);
	newnode->next = *sl;
	*sl = newnode;
}
void SLPopBack(SL** sl)
{
	assert(sl && *sl);
	if ((*sl)->next == NULL)
	{
		free(*sl);
		*sl = NULL;
	}
	else
	{
		SL* ptail = *sl;
		SL* prev = *sl;
		while (ptail->next)
		{
			prev = ptail;
			ptail = ptail->next;
		}
		free(ptail);
		ptail = NULL;
		prev->next = NULL;
	}
}
void SLPopFront(SL** sl)
{
	assert(sl && *sl);
	SL* ptail = *sl;
	*sl = ptail->next;
	free(ptail);
	ptail = NULL;
}
SL* SLFind(SL** sl, SLDateType index)
{
	assert(sl && *sl);
	SL* ptail = *sl;
	while (ptail)
	{
		if (ptail->date == index)
		{
			return ptail;
		}
		ptail = ptail->next;
	}
	return NULL;
}
void SLInsert(SL** sl, SL* pos, SLDateType index)
{
	assert(sl && *sl && pos);
	SL* newnode = BuyNode(index);
	if (*sl == pos)
	{
		SLPushFront(sl, index);
	}
	else
	{
		SL* prev = *sl;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = newnode;
		newnode->next = pos;
	}
}
void SLErase(SL** sl, SL* pos)
{
	assert(sl && *sl && pos);
	SL* ptail = *sl;
	if (*sl == pos)
	{
		*sl = ptail->next;
		free(ptail);
		ptail = NULL;
	}
	else
	{
		while (ptail->next != pos)
		{
			ptail = ptail->next;
		}
		ptail->next = pos->next;
		free(pos);
		pos = NULL;
	}
	
}
void SLInsertAfter(SL* pos, SLDateType index)
{
	assert(pos);
	SL* newnode = BuyNode(index);
	newnode->next = pos->next;
	pos->next = newnode;
}
void SLEraseAfter(SL* pos)
{
	assert(pos && pos->next);
	SL* ptail = pos->next;
	pos->next = pos->next->next;
	free(ptail);
	ptail = NULL;
}
void SListDesTroy(SL** sl)
{
	assert(sl && *sl);
	SL* ptail = *sl;
	while (ptail)
	{
		SL* prev = ptail ->next;
		free(ptail);
		ptail = prev;
	}
	*sl = NULL;
}